import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { validateExpenseInput, expenseSchema } from '@/lib/validators/expense';
import { parse } from 'date-fns';

// GET /api/expenses - 获取支出列表
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const siteId = searchParams.get('siteId');
    const expenseId = searchParams.get('id');

    if (expenseId) {
      const expense = await prisma.expense.findUnique({
        where: { id: expenseId },
      });

      if (!expense) {
        return NextResponse.json(
          { error: '支出记录不存在' },
          { status: 404 }
        );
      }

      return NextResponse.json(expense);
    }

    const expenses = await prisma.expense.findMany({
      where: siteId ? { siteId } : undefined,
      orderBy: {
        paymentDate: 'desc',
      },
    });

    return NextResponse.json(expenses);
  } catch (error) {
    console.error('获取支出列表失败:', error);
    return NextResponse.json(
      { error: '获取支出列表失败' },
      { status: 500 }
    );
  }
}

// POST /api/expenses - 创建新支出
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    // 验证输入数据
    const validation = await validateExpenseInput(body);
    if (!validation.success) {
      return NextResponse.json(
        { error: validation.error },
        { status: 400 }
      );
    }

    const { siteId, type, amount, paymentDate, vendor, description } = validation.data;

    // 检查工地是否存在
    const site = await prisma.site.findUnique({
      where: { id: siteId },
    });

    if (!site) {
      return NextResponse.json(
        { error: '工地不存在' },
        { status: 404 }
      );
    }

    // 创建支出记录
    const expense = await prisma.expense.create({
      data: {
        siteId,
        type,
        amount,
        paymentDate: parse(paymentDate, 'yyyy-MM-dd', new Date()),
        vendor,
        description,
      },
    });

    return NextResponse.json(expense);
  } catch (error) {
    console.error('创建支出失败:', error);
    return NextResponse.json(
      { error: '创建支出失败' },
      { status: 500 }
    );
  }
}

// PUT /api/expenses/[expenseId] - 更新支出
export async function PUT(
  request: NextRequest
) {
  try {
    const body = await request.json();
    const validation = await expenseSchema.partial().safeParseAsync(body);
    const expenseId = request.url.split('/').pop();

    if (!validation.success) {
      return NextResponse.json(
        { error: validation.error.errors[0] },
        { status: 400 }
      );
    }

    const updateData = {
      ...validation.data,
      ...(validation.data.paymentDate && {
        paymentDate: parse(validation.data.paymentDate, 'yyyy-MM-dd', new Date())
      })
    };

    const expense = await prisma.expense.update({
      where: { id: expenseId },
      data: updateData,
    });

    return NextResponse.json(expense);
  } catch (error) {
    console.error('更新支出失败:', error);
    if (error instanceof Error && error.message.includes('Record to update not found')) {
      return NextResponse.json(
        { error: '支出记录不存在' },
        { status: 404 }
      );
    }
    return NextResponse.json(
      { error: '更新支出失败' },
      { status: 500 }
    );
  }
}

// DELETE /api/expenses/[expenseId] - 删除支出
export async function DELETE(
  request: NextRequest
) {
  try {
    const expenseId = request.url.split('/').pop();
    const expense = await prisma.expense.delete({
      where: { id: expenseId },
    });

    return NextResponse.json(expense);
  } catch (error) {
    console.error('删除支出失败:', error);
    if (error instanceof Error && error.message.includes('Record to delete does not exist')) {
      return NextResponse.json(
        { error: '支出记录不存在' },
        { status: 404 }
      );
    }
    return NextResponse.json(
      { error: '删除支出失败' },
      { status: 500 }
    );
  }
} 